#if UNITY_EDITOR

using UnityEngine;
using UnityEditor;

namespace Core
{
    public class AssetSystemEditor : EntitySystem, IAwake
    {
        public void Awake()
        {
            Subscribe<DecompressStreamingAssets>(DecompressStreamingAssets);
            Subscribe<UpdateAssetsVersion>(UpdateAssetsVersion);
            SubscribeAllLoadAssetEvent();
        }

        private void SubscribeAllLoadAssetEvent()
        {
            SubscribeLoadAsset<UnityEngine.Object>();
            SubscribeLoadAsset<GameObject>();
            SubscribeLoadAsset<Material>();
            SubscribeLoadAsset<Texture2D>();
            SubscribeLoadAsset<Texture>();
            SubscribeLoadAsset<Shader>();
            SubscribeLoadAsset<TextAsset>();
            SubscribeLoadAsset<Sprite>();
        }

        public void SubscribeLoadAsset<T>() where T : UnityEngine.Object
        {
            Subscribe<LoadAssetAsync<T>>(LoadAssetAsync);
            Subscribe<LoadAsset<T>>(LoadAsset);
        }

        private void DecompressStreamingAssets(ref DecompressStreamingAssets data)
        {
            new OnDecompressStreamingAssetsComplete().Publish();
        }

        private void UpdateAssetsVersion(ref UpdateAssetsVersion data)
        {
            new OnUpdateAssetsVersionComplete().Publish();
        }

        internal void LoadAsset(ref LoadAsset<UnityEngine.Object> data)
        {
            data.asset = LoadAsset<Object>((string)data.assetPath);
        }

        internal void LoadAsset<T>(ref LoadAsset<T> data) where T : UnityEngine.Object
        {
            data.asset = LoadAsset<T>((string)data.assetPath);
        }

        internal async ETTask<LoadAssetAsync<UnityEngine.Object>> LoadAssetAsync(LoadAssetAsync<UnityEngine.Object> data)
        {
            await ETTask.CompletedTask;
            data.asset = LoadAsset<UnityEngine.Object>((string)data.assetPath);
            return data;
        }

        internal async ETTask<LoadAssetAsync<T>> LoadAssetAsync<T>(LoadAssetAsync<T> data) where T : UnityEngine.Object
        {
            await ETTask.CompletedTask;
            data.asset = LoadAsset<T>((string)data.assetPath);
            return data;
        }

        private T LoadAsset<T>(string assetPath) where T : UnityEngine.Object
        {
            var projectPath = $"Assets/{GameConst.PACKAGE_PATH}/{assetPath}";

            var asset = AssetDatabase.LoadAssetAtPath<T>(projectPath);
            if (asset != null)
                return asset;

            Debug.LogError($"can not find asset at path:{projectPath}");
            return null;
        }
    }
}

#endif